$(document).ready(function () {

    // 告警列表
    initlarmModuleListRender(rightFloorArr);
    initModule();

    // 放大缩小
    new windowAdaption().zoomin();
    // 窗口大小自适应
    $(window).resize(function () {
        new windowAdaption().zoomin();
    });

    // 菜单点击
    $(document).on("click","#left-menu-secondary a",function(e){
        if(!$(this).hasClass('selected')){
            var deviceType = $(this).attr("datatype");
            seleAlarmModel(deviceType);
        }
    });

    // 获取数据
    getAlarmData();

    // 主页模块点击
    $(document).on("click","#alarm-model-box .alarm-model",function(){
        if($("#alarm-table-box").hasClass("hide")){
            var deviceType = $(this).attr("datatype");
            var tableCode = $(this).attr("tableCode");
            // var page = $(this).attr("page");
            var alarmEle = $(this).find('i')

            if(tableCode == "wait" || deviceType == ""){
                return tipModal("icon-cross", "设备安装调试中");
            }

            if (alarmEle.length) {
                $(this).find('i').remove()
                // 清楚警告信息
                clearAlarmInfo(deviceType)
            }

            // if (tableCode == 'special') {
            //     var url = window.location.origin + window.location.pathname
            //     return window.location.href = url.slice(0, url.lastIndexOf('/') + 1) + page + window.location.search.slice(0, 11)
            // }

            $("#left-menu-secondary li").removeClass("selected");
            $("#left-menu-secondary a").find('span.deviceLiIcon').removeClass('icon-circle-right');
            $("#left-menu-secondary a").each(function(){
                var datatype = $(this).attr("datatype");
                if(deviceType == datatype){
                    $(this).parents("li").addClass("selected");
                    $(this).find('span.deviceLiIcon').addClass('icon-circle-right');
                }
            });
            seleAlarmModel(deviceType);
        }
    });

    // 动环详情展示
    window.showDetail = function(warningId) {
        // detTemplate
        // PostForm("/cwp/front/sh/serverService!execute", "uid=dems003&id=" + warningId, "", function(result) {
        //     if (+result.returnCode) {
        //         tipModal("icon-cross", '数据查询失败!');
        //         return;
        //     }
        //
        //     // 模板引擎
        //     var html = template('detTemplate', result)
        //
        //     $('#modalRingDet .t-columns-group').html(html)
        //
        //     $("#modalRingDet").modal({
        //         keyboard: true,
        //         backdrop: 'static'
        //     }).on('show.bs.modal', centerModal())
        //     $(window).on('resize', centerModal())
        // }, '');
        $.getJSON('/cwp/src/json/warning/serverService_dems003.json',function(result){
            if (+result.returnCode) {
                tipModal("icon-cross", '数据查询失败!');
                return;
            }

            // 模板引擎
            var html = template('detTemplate', result)

            $('#modalRingDet .t-columns-group').html(html)

            $("#modalRingDet").modal({
                keyboard: true,
                backdrop: 'static'
            }).on('show.bs.modal', centerModal())
            $(window).on('resize', centerModal())
        })
    }

    // 每分钟轮询
    setInterval(function() {
        getAlarmInfo()
    }, 1000 * 60)
});

//告警列表选中
var initModule = function() {
    var indexStr = window.location.search.split('&')[1]

    if (indexStr) {
        var index = (indexStr.split('=')[1])
        $("#left-menu-secondary li:eq(" + index +") a").click()
    } else {
        $("#left-menu-secondary li").eq(0).addClass("selected").find('span.deviceLiIcon').addClass('icon-circle-right');
    }
}



// 主面板
var monitoringPanel = document.getElementById("monitoring-panel");
var menuLeftWidth = 325;
var windowAdaption = function(){
    this.state = {
        sizeWidth : 1.0,
        sizeHeight : 1.0,
        screenHeight : window.innerHeight - 90,
        screenWidth : window.innerWidth - menuLeftWidth,
        height:( 1080 - 18 ) * (Math.ceil(($('#alarm-model-box').children().length - 1 ) / 4) / 3) + 18*($('#alarm-model-box').children().length>0?1:0)
    };
    this.zoomin = function() {
        this.state.screenHeight = window.innerHeight - 90;
        this.state.screenWidth = window.innerWidth - menuLeftWidth;
        this.state.sizeWidth = this.state.screenWidth / 1920;
        this.state.sizeHeight = this.state.screenHeight / 1080;
        // $('#alarm-table-box').parent().css('margin-top',(- 372 + this.state.height*this.state.sizeHeight) + "px");
        monitoringPanel.style.overflow = "hidden";
        monitoringPanel.style.width = 1920 + "px";
        monitoringPanel.style.height = this.state.height + "px";
        monitoringPanel.style.transform="scale("+this.state.sizeWidth + "," + this.state.sizeHeight+")";
        monitoringPanel.style.transformOrigin="0 0";
    };
};

// 选择告警设备
var seleAlarmModel = function(deviceType){
    if(deviceType == '0'){
        initlarmModuleListRender(rightFloorArr);
        getAlarmData();
        $("#alarm-table-box").addClass("hide");
    }else{
        $("#alarm-model-box").html('');
        $("#alarm-table-box").removeClass("hide");
        //故障告警列表
        $("#faultAlarmTab").html("");
        dictValue = deviceType;
        faultAlarmList(1);
    }
    new windowAdaption().zoomin();
};



// 告警设备类别
var dictValue = "";
// 告警主页列表详细
var initlarmModules = function(value){
    var alarmModules = '';
    var contentLength = value.content.length;
    var detailLength = 0;
    value.content.forEach(function (v) {
        detailLength += v.detail.length;
    });
    value.content.forEach(function (v) {
        var tDetailLength = v.detail.length;
        alarmModules += "<div class='alarm-model-body-div' data-height='" + contentLength + "-" + detailLength + "-" + tDetailLength + "'><div class='alarm-model-body-div-title'>" + v.title + "</div><div class='alarm-model-body-div-content'>";
        v.detail.forEach(function (v2) {
            alarmModules += "<div class='alarm-model-body-div-content-child'><span class='alarm-model-body-div-type'>" + v2.type + "</span><span class='alarm-model-body-div-count' dataCode='" + value.deviceType + "-" + v2.code + "'>" + v2.count + "</span><span class='alarm-model-body-div-unit'>" + v2.unit + "</span></div>";
        });
        alarmModules += "</div></div>";
    });
    return alarmModules;
};
// 告警主页列表组装
var initlarmModuleList = function (dataArr) {
    for(var i = 0; i < dataArr.length; i++){
        if(dataArr[i].deviceType == '0'){
            dataArr.splice(i,1);
            break;
        }
    }
    var alarmModuleList = "";
    dataArr.forEach(function(value) {
        alarmModuleList += "<div class='alarm-model alarm-model-" + value.deviceType + "' dataType='" + value.deviceType + "' tableCode='" + (value.tableCode?value.tableCode:'')
        // special 页面
        if (value.page) {
            alarmModuleList += "' page='" + value.page
        }
        alarmModuleList += "'><div class='alarm-model-title' style='position: relative; background-color: " + value.bgColor + "'>" + value.deviceName + "</div><div class='alarm-model-body' style='border-left-color: " + value.bgColor + "'>";
        alarmModuleList += initlarmModules(value);
        alarmModuleList += "</div></div>";
    });

    alarmModuleList += "<div class='clearfix'></div>";
    return alarmModuleList;
};
// 格式化
var initlarmModuleListFormat = function(_this){
    var heightPropArr = _this.attr('data-height').split('-');
    var bodyHeight = $('.alarm-model-body').height() - (heightPropArr[0] - 1) * 5;
    var titleHeight = heightPropArr[2] / heightPropArr[1] * bodyHeight;
    _this.find('.alarm-model-body-div-title').height(titleHeight).css("line-height", titleHeight + 'px');
    var childHeight = bodyHeight / heightPropArr[1];
    _this.find('.alarm-model-body-div-content-child').height(childHeight).css("line-height", childHeight + 'px');
};
// 告警主页列表渲染
var initlarmModuleListRender = function(dataArr){
    $("#alarm-model-box").html(initlarmModuleList(dataArr));
    $(".alarm-model-body").find('.alarm-model-body-div').each(function(){
        var _this = $(this);
        initlarmModuleListFormat(_this);
    });
};
// 获取数据
var getAlarmData = function(){
    // 汇总
    // PostForm("/cwp/front/sh/warningEvent!execute", "uid=wd001", "", function(result){
    //     if(result.returnCode == 0){
    //         renderAlarmData(result.beans);
    //     }
    // });
    $.getJSON('/cwp/src/json/warning/warningEvent_wd001.json',function(result){
        if(result.returnCode == 0){
            renderAlarmData(result.beans);
        }
    })

    // 停车场
    var createTime = function(){
        var d = new Date();
        var t = d.getTime();
        d.setTime(t-24*60*60*1000);
        var y = d.getFullYear();
        var m = d.getMonth() + 1;
        var day = d.getDate();
        m = m<10?'0'+m:m;
        day = day<10?'0'+day:day;
        return y + '-' + m + '-' + day;
    };
    // PostForm("/cwp/front/sh/warningEvent!execute", "uid=car003&dateTime=" + createTime(), "", function(result){
    //     if(result.returnCode == 0){
    //         var carCount = result.bean.carCount;
    //         if(carCount == undefined){
    //             carCount = 0;
    //         }
    //         $("#alarm-model-box").find('.alarm-model').find('.alarm-model-body-div-count').each(function(){
    //             var dataCode = $(this).attr('datacode');
    //             if(dataCode == '11-11-carsNum'){
    //                 $(this).text(carCount);
    //             }
    //         })
    //     }
    // });
    $.getJSON('/cwp/src/json/warning/warningEvent_car003.json',function(result){
        if(result.returnCode == 0){
            var carCount = result.bean.carCount;
            if(carCount == undefined){
                carCount = 0;
            }
            $("#alarm-model-box").find('.alarm-model').find('.alarm-model-body-div-count').each(function(){
                var dataCode = $(this).attr('datacode');
                if(dataCode == '11-11-carsNum'){
                    $(this).text(carCount);
                }
            })
        }
    })


    // 能耗管理
    var monthTime = function(){
        var d = new Date();
        var y = d.getFullYear();
        var m = d.getMonth()+ 1;
        (m>1) ? m -= 1 : (m = 12,y -= 1);
        m = m<10?'0'+m:m;
        return y + '-' + m;
    };
    // PostForm("/cwp/front/sh/device!execute", "uid=ele003&monthTime=" + monthTime(), "", function(result){
    //     if(result.returnCode == 0){
    //         var value = {};
    //         value.content = [];
    //         for(var i = 0 ; i < result.beans.length && i < 4 ; i ++ ){
    //             value.content[i] = {
    //                 title:result.beans[i].deviceName,
    //                 detail:[
    //                     {
    //                         type: '度数',
    //                         unit: 'KW/H',
    //                         code: 'null-餐厅二楼电表',
    //                         count: result.beans[i].powerFactor
    //                     }
    //                 ]
    //             }
    //         }
    //         $(".alarm-model-1006 .alarm-model-body").html(initlarmModules(value))
    //         $(".alarm-model-1006").find('.alarm-model-body-div').each(function () {
    //             var _this = $(this);
    //             initlarmModuleListFormat(_this);
    //         });
    //     }
    // });
    $.getJSON('/cwp/src/json/warning/warningEvent_ele003.json',function(result){
        if(result.returnCode == 0){
            var value = {};
            value.content = [];
            for(var i = 0 ; i < result.beans.length && i < 4 ; i ++ ){
                value.content[i] = {
                    title:result.beans[i].deviceName,
                    detail:[
                        {
                            type: '度数',
                            unit: 'KW/H',
                            code: 'null-餐厅二楼电表',
                            count: result.beans[i].powerFactor
                        }
                    ]
                }
            }
            $(".alarm-model-1006 .alarm-model-body").html(initlarmModules(value))
            $(".alarm-model-1006").find('.alarm-model-body-div').each(function () {
                var _this = $(this);
                initlarmModuleListFormat(_this);
            });
        }
    })


    //动环
    // PostForm("/cwp/front/sh/warningEvent!execute", "uid=wd004", "post", function(result){
    //     if(result.returnCode == 0){
    //         $("#alarm-model-box").find('.alarm-model').find('.alarm-model-body-div-count').each(function(){
    //             var _this = $(this);
    //             var dataCode = $(this).attr('datacode');
    //             result.beans.forEach(function (value) {
    //                 if(dataCode == ('1003191-ring-' + value.maintenanceRate)){
    //                     _this.text(value.count);
    //                 }
    //             })
    //         })
    //     }
    // });
    $.getJSON('/cwp/src/json/warning/warningEvent_wd004.json',function(result){
        if(result.returnCode == 0){
            $("#alarm-model-box").find('.alarm-model').find('.alarm-model-body-div-count').each(function(){
                var _this = $(this);
                var dataCode = $(this).attr('datacode');
                result.beans.forEach(function (value) {
                    if(dataCode == ('1003191-ring-' + value.maintenanceRate)){
                        _this.text(value.count);
                    }
                })
            })
        }
    })

};
// 告警主页数据渲染
var renderAlarmData = function(data){
    $("#alarm-model-box").find('.alarm-model').find('.alarm-model-body-div-count').each(function(){
        var dataCode = $(this).attr('datacode').split('-');
        var dataType = dataCode[0];
        var dataZone = dataCode[1];
        var dataName = dataCode[2];
        var _this = $(this);
        data.forEach(function(value){
            if(value.deviceType == dataType && value.zone == dataZone){
                for(key in value){
                    if(key == dataName){
                        _this.text(value[key]);
                        break;
                    }
                }
            }
        });
    })

    // 获取新的告警信息
    getAlarmInfo()
};


/**************** 告警声音 *********************/
// 获取告警信息
var getAlarmInfo = function() {
    // PostForm('/cwp/front/sh/warningEvent!execute', "uid=wd002", '', function (result) {
    //     if (result.returnCode == 0) {
    //         var data = result.beans
    //         var obj = {}
    //         var alarmVoiceFlag = false;
    //
    //         for(var i = 0, len = data.length; i < len; i++) {
    //             if (data[i].count > 0) {
    //                 obj[data[i].deviceTypeId] = '1'
    //                 alarmVoiceFlag = true;
    //             }
    //         }
    //
    //         var dataType;
    //         $('#alarm-model-box .alarm-model').each(function(index, ele) {
    //             var alarmEle = $(ele).find('i')
    //             dataType = $(ele).attr('datatype')
    //
    //             if (!alarmEle.length != !obj[dataType]) {
    //                 if (obj[dataType]) {
    //                     $(ele).find('.alarm-model-title').append('<i class="t-badge-orange warn-info t-alarm-panel">!</i>')
    //                 } else {
    //                     alarmEle.remove()
    //                 }
    //             }
    //         })
    //
    //         // 播放告警声音
    //         if (alarmVoiceFlag) {
    //             alarmVoice()
    //         }
    //     }
    // })

    $.getJSON('/cwp/src/json/warning/warningEvent_wd002.json',function(result){
        if (result.returnCode == 0) {
            var data = result.beans
            var obj = {}
            var alarmVoiceFlag = false;

            for(var i = 0, len = data.length; i < len; i++) {
                if (data[i].count > 0) {
                    obj[data[i].deviceTypeId] = '1'
                    alarmVoiceFlag = true;
                }
            }

            var dataType;
            $('#alarm-model-box .alarm-model').each(function(index, ele) {
                var alarmEle = $(ele).find('i')
                dataType = $(ele).attr('datatype')

                if (!alarmEle.length != !obj[dataType]) {
                    if (obj[dataType]) {
                        $(ele).find('.alarm-model-title').append('<i class="t-badge-orange warn-info t-alarm-panel">!</i>')
                    } else {
                        alarmEle.remove()
                    }
                }
            })

            // 播放告警声音
            if (alarmVoiceFlag) {
                alarmVoice()
            }
        }
    })
}

/**
 * 清空告警信息
 * @param deviceType 设备类型，模块类型
 */
var clearAlarmInfo = function(deviceType) {
    // PostForm('/cwp/front/sh/warningEvent!execute', 'uid=wd003&warningType=' + deviceType, 'get')

    $.getJSON('/cwp/src/json/warning/warningEvent_wd003.json',function(data){

    })
}

// 告警声音处理
var alarmVoice = function() {

    if ($('#alarm-voice').html() == '') {
        if ($.browser && $.browser.msie && $.browser.version == '8.0') {
            $('#alarm-voice').html('<embed id="player" src="warn.wav"/>');
        } else {
            $('#alarm-voice').html('<audio id="player" src="../../../assets/voice/warn.wav"></audio>');
        }

        alarmLoop()
    } else {
        alarmLoop()
    }
}

// 告警循环
var alarmLoop = function() {

    var loopInt = setInterval(function() {
        $('#player')[0].play()
    }, 1000 * 1.5)

    // 响五声警报
    setTimeout(function() {
        clearInterval(loopInt)
    }, 1000 * 14)

}
/**************** /告警声音 *********************/